package se.quiz.cliente;

import org.json.JSONException;
import org.json.JSONObject;

import se.quiz.cliente.R;
import se.quiz.cliente.conexao.HttpManager;
import se.quiz.cliente.conexao.PacoteRequisicao;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class CadastrarSe extends Activity {
	
	private Tarefa tarefa;
	private ProgressBar pb;
	private String persistencia = null;
	private EditText etUsuario;
	EditText etSenha;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cadastrar_se);
		
		pb = (ProgressBar) findViewById(R.id.pbCadastrarSe);
		pb.setVisibility(View.INVISIBLE);
		
		etUsuario = (EditText) findViewById(R.id.etCriarUsuario);
		etSenha = (EditText)findViewById(R.id.etCampoCriarSenha);
		
		Button btnVoltar = (Button)findViewById(R.id.btnVoltarCadastrarSe);
		btnVoltar.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(CadastrarSe.this, Inicial.class));				
			}
		});
		
		Button btnCriarLogin = (Button)findViewById(R.id.btnCriarLogin);
		btnCriarLogin.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				etUsuario = (EditText) findViewById(R.id.etCriarUsuario);
				String usuario = etUsuario.getText().toString();
				etSenha = (EditText)findViewById(R.id.etCampoCriarSenha);
				String senha = etSenha.getText().toString();
				if(usuario.length()>=3 && senha.length()>=3){
					tarefa = new Tarefa();
					pb.setVisibility(View.VISIBLE);						
					tarefa = new Tarefa();
					PacoteRequisicao pacote = new PacoteRequisicao();
					pacote.setMethod("POST");
					pacote.setUri("http://"+Inicial.ipServidor+":"+Inicial.portaServidor+"/QuizServer/ServletCadastrarSe");
					pacote.setParametro("usuario", usuario);
					pacote.setParametro("senha", senha);
					tarefa.execute(pacote);	
					
				}else{
					Toast.makeText(getApplicationContext(), "Preencha todos os campos(3 caracteres pelo menos)", Toast.LENGTH_SHORT).show();
				}
				
				
			}
		});
	}
	
	private class Tarefa extends AsyncTask<PacoteRequisicao, String, String>{

		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected String doInBackground(PacoteRequisicao... params) {
			
			try {
				JSONObject json = new JSONObject(HttpManager.getData(params[0]));
				persistencia = json.getString("message"); 
//				Log.i("logquiz",json.getString("message"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {			
			pb.setVisibility(View.INVISIBLE);	
				
			if(Boolean.parseBoolean(persistencia)){
				etSenha.setText("");
				etUsuario.setText("");
				Toast.makeText(getApplicationContext(), "Usuario incluido com sucesso", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(), "Usuario ja existe na base", Toast.LENGTH_SHORT).show();
				etUsuario.setText("");
				etSenha.setText("");
				etUsuario.requestFocus();
			}			
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.cadastrar, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
